package searcher;

import java.io.File;
import java.sql.ResultSet;
import java.util.Date;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import database.Dao;

public class Index {
	private Logger log = Logger.getLogger(Index.class);
	
	//private final String INDEXPATH = this.getClass().getClassLoader().getResource("/").getPath();

	public boolean createIndex() {

		Dao dao = new Dao();

		ResultSet rs = dao.select("select id,text from grass");

		try {
			Directory directory = new SimpleFSDirectory(new File(this.getClass().getResource("/").getPath()+"/index"));
			Analyzer an = new IKAnalyzer();
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_31,
					an);
			IndexWriter indexWriter = new IndexWriter(directory, iwc);

			long begin = new Date().getTime();
			while (rs.next()) {
				Document doc = new Document();
				Integer id = rs.getInt(1);
				String text = rs.getString(2);
				doc.add(new Field("id", id.toString(), Field.Store.YES,
						Field.Index.ANALYZED, Field.TermVector.YES));

				doc.add(new Field("text", text, Field.Store.YES,
						Field.Index.ANALYZED, Field.TermVector.YES));
				indexWriter.addDocument(doc);
			}

			long end = new Date().getTime();
			log.info(">>> 1.存入索引完毕.. 共花费：" + (end - begin) + "毫秒...");

			indexWriter.optimize();
			indexWriter.close();
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
}
